﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.RegistrationCommand;
using D.Medicalcare.Read.API.Dtos;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.RegistrationHandler
{
    /// <summary>
    /// 处理挂号信息
    /// </summary>
    public class GetRegistrationHandler : IRequestHandler<GetRegistrationCommand, APIPaging<RegistrationDTO>>
    {
        private readonly IBaseRepository<Registration> rrep;
        private readonly IBaseRepository<DoctorScheduling> srep;
        private readonly IBaseRepository<Doctor> drep;
        private readonly IBaseRepository<Department> prep;
        private readonly IBaseRepository<TitleManagement> trep;
        private readonly IBaseRepository<HospitalNavigation> hrep;
        private readonly IBaseRepository<Patient> patientrep;
        private readonly ILogger<GetRegistrationHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="rrep"></param>
        /// <param name="srep"></param>
        /// <param name="drep"></param>
        /// <param name="prep"></param>
        /// <param name="trep"></param>
        /// <param name="hrep"></param>
        /// <param name="patientrep"></param>
        public GetRegistrationHandler(IBaseRepository<Registration> rrep, IBaseRepository<DoctorScheduling> srep,
            IBaseRepository<Doctor> drep, IBaseRepository<Department> prep, IBaseRepository<TitleManagement> trep,
            IBaseRepository<HospitalNavigation> hrep, IBaseRepository<Patient> patientrep,ILogger<GetRegistrationHandler> logger)
        {
            this.rrep = rrep;
            this.srep = srep;
            this.drep = drep;
            this.prep = prep;
            this.trep = trep;
            this.hrep = hrep;
            this.patientrep = patientrep;
            this.logger = logger;
        }
        /// <summary>
        /// 查询挂号信息
        /// </summary>
        public Task<APIPaging<RegistrationDTO>> Handle(GetRegistrationCommand request, CancellationToken cancellationToken)
        {
            APIPaging<RegistrationDTO> result = new APIPaging<RegistrationDTO>();
            try
            {
                var m = from a in rrep.GetAll()
                        join b in drep.GetAll() on a.DoctorId equals b.DoctorId into doctorJoin
                        from b in doctorJoin.DefaultIfEmpty()
                        join c in srep.GetAll() on b.DoctorId equals c.DoctorId into schedulingJoin
                        from c in schedulingJoin.DefaultIfEmpty()
                        join d in prep.GetAll() on b.DeparId equals d.DeparId into departmentJoin
                        from d in departmentJoin.DefaultIfEmpty()
                        join e in trep.GetAll() on b.TitlemanagementId equals e.TitleManagementId into titleJoin
                        from e in titleJoin.DefaultIfEmpty()
                        join f in hrep.GetAll() on d.CampusId equals f.HospitalNavigationId into hospitalJoin
                        from f in hospitalJoin.DefaultIfEmpty()
                        join g in patientrep.GetAll() on a.PatientId equals g.PatientId into patientJoin
                        from g in patientJoin.DefaultIfEmpty()
                        select new RegistrationDTO
                        {
                            RegistrationId = a.RegistrationId,
                            CampusName = f.CampusName,
                            AddressCampus = f.AddressCampus,
                            PatientName = g.PatientName,
                            PatientNo = g.PatientNo,
                            DocumentNo = g.DocumentNo,
                            Phone = g.Phone,
                            DeparId=d.DeparId,
                            DeparName = d.DeparName,
                            DoctorName = b.DoctorName,
                            JobName = e.JobName,
                            Registrationfee = b.Registrationfee,
                            RegistrationType = a.RegistrationType,
                            Statue = a.Statue,
                            RegistrationTime = a.RegistrationTime,
                            Mtime = a.Mtime,
                            WaitTime = a.WaitTime,
                            UpdateTime = a.UpdateTime,
                            UpdateReson = a.UpdateReson,
                            Doctorlocation = d.Doctorlocation
                        };
                if (!string.IsNullOrEmpty(request.Statue))
                {
                    m=m.Where(x => x.Statue==request.Statue);
                }
                if (!string.IsNullOrEmpty(request.DoctorName))
                {
                    m = m.Where(x => x.DoctorName == request.DoctorName);
                }
                if (!string.IsNullOrEmpty(request.PatientName))
                {
                    m=m.Where(x => x.PatientName == request.PatientName);
                }
                if (!string.IsNullOrEmpty(request.StartTime))
                {
                    m = m.Where(x=>x.RegistrationTime>=DateTime.Parse(request.StartTime));
                }
                if (!string.IsNullOrEmpty(request.EndTime))
                {
                    m = m.Where(x => x.RegistrationTime < DateTime.Parse(request.EndTime));
                }
                if (request.DeparId>0)
                {
                    m = m.Where(x=>x.DeparId==request.DeparId);
                }
                logger.LogInformation("查询成功");
                result.Count = m.Count();
                result.PageCount = (int)Math.Ceiling(result.Count * 1.0 / request.PageSize);
                result.Data = m.OrderByDescending(x => x.RegistrationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error: {ex.Message}");
                throw;
            }
           
        }
    }
}
